<template>
  <view class="box" :style="customBoxStyle">
    <view
      class="tag"
      @tap.stop="click(item)"
      :style="item.checked ? customCheckStyle : customStyle"
      v-for="(item, index) in singleList"
      :key="index"
    >
      {{ item.label }}
    </view>
  </view>
</template>

<script>
export default {
  name: "chooseBtn",
  props: {
    // 自定义按钮样式，对象形式
    customStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    customCheckStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    // 自定义盒子样式，对象形式
    customBoxStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    list: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      obj: {}, //选择的对象
      singleList: [],
    };
  },
  watch: {
    list: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.length) {
          this.singleList = this.list;
        }
      },
    },
  },
  mounted() {},
  methods: {
    click(e) {
      let newList = this.singleList;
      newList.forEach((element, index) => {
        if (e.id === element.id) {
          newList[index].checked = !newList[index].checked;
          return;
        }
        newList[index].checked = false;
      });
      this.singleList = [];
      this.singleList = newList;
      this.singleList.forEach((element) => {
        if (element.checked === true) {
          this.obj = element;
          return;
        }
      });
      this.$emit("click", this.obj);
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
  .tag {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 1rem;
  }
}
</style>
